package ar.camera.surfaceview;

import java.io.IOException;

import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;

public class CameraSurfaceView extends SurfaceView implements Callback {

	private final String TAG = "CameraView";
	public Camera camera;
	private int orientation = 0;

	public CameraSurfaceView(Context context, int orientation) {
		super(context);

		this.orientation = orientation;
		getHolder().addCallback(this);
		getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		camera = getCameraInstance();
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {

		if (camera == null)
			return;

		if (getHolder().getSurface() == null) {
			return;
		}
		try {
			camera.stopPreview();
		} catch (Exception e) {
			Log.e(TAG, "Exception caused by surfaceChanged()", e);
		}

		// here

		try {
			camera.setPreviewDisplay(getHolder());
			camera.startPreview();
		} catch (IOException e) {
			Log.e(TAG, "IOException caused by surfaceCreated()", e);
		}
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		if (camera != null) {
			camera.stopPreview();
			camera.release();
			camera = null;
		}

	}

	public void releaseCam() {
		if (camera != null) {
			camera.stopPreview();
			camera.release();
			camera = null;
		}
	}

	public Camera getCameraInstance() {
		Camera c = null;
		if (camera != null)
			surfaceDestroyed(null);
		try {
			c = Camera.open();
			Camera.Parameters params = c.getParameters();
			params.set("orientation", "portrait");
			params.setRotation(0);
			params.setPictureSize(
					params.getSupportedPictureSizes().get(0).width, params
							.getSupportedPictureSizes().get(0).height);
			params.setPreviewSize(
					params.getSupportedPreviewSizes().get(3).width, params
							.getSupportedPreviewSizes().get(3).height);
			c.setParameters(params);
			c.setDisplayOrientation(this.orientation);

		} catch (Exception e) {
			Log.e(TAG, "Exception caused by getCameraInstance()", e);
		}
		return c;
	}

	public boolean checkCameraHardware(Context context) {
		if (context.getPackageManager().hasSystemFeature(
				PackageManager.FEATURE_CAMERA)) {
			return true;
		} else {
			return false;
		}
	}
}
